#include "Book.h"
#include <sstream>

namespace library {

// 构造函数：初始化图书的所有属性
Book::Book(int id, const std::string& name, const std::string& author, int stock)
    : id(id), name(name), author(author), totalStock(stock), currentStock(stock) {}

// 设置总库存，同时确保当前库存不超过总库存
void Book::setTotalStock(int stock) {
    totalStock = stock;
    if (currentStock > totalStock) {
        currentStock = totalStock;  // 如果当前库存超过新的总库存，则调整为总库存
    }
}

// 借出图书，成功返回true，失败返回false
bool Book::borrow(int quantity) {
    if (quantity <= currentStock) {  // 检查是否有足够的库存
        currentStock -= quantity;     // 减少当前库存
        return true;
    }
    return false;  // 库存不足，无法借出
}

// 归还图书，成功返回true，失败返回false
bool Book::returnBook(int quantity) {
    if (currentStock + quantity <= totalStock) {  // 检查归还后是否超过总库存
        currentStock += quantity;                  // 增加当前库存
        return true;
    }
    return false;  // 归还数量过多，超过总库存
}

// 将图书信息转换为字符串，用于保存到文件
std::string Book::toString() const {
    std::stringstream ss;
    // 格式：ID,书名,作者,总库存,当前库存
    ss << id << "," << name << "," << author << "," << totalStock << "," << currentStock;
    return ss.str();
}

} // namespace library 